#include "../include/registerwidget.h"
#include "../include/config.h"
#include <QMessageBox>
#include <QRegularExpression>
#include <QFont>
#include <QTimer>

RegisterWidget::RegisterWidget(AuthService *authService, QWidget *parent)
    : QWidget(parent)
    , m_authService(authService)
    , m_primaryColor("#4A90E2")
    , m_secondaryColor("#7ED321")
    , m_backgroundColor("#2C3E50")
    , m_textColor("#ECF0F1")
    , m_errorColor("#E74C3C")
    , m_successColor("#27AE60")
    , m_warningColor("#F39C12")
{
    setupUI();
    applyStyles();

    connect(m_authService, &AuthService::registerSucceeded,
            this, &RegisterWidget::onRegisterSucceeded);
    connect(m_authService, &AuthService::registerFailed,
            this, &RegisterWidget::onRegisterFailed);
}

RegisterWidget::~RegisterWidget()
{
    // 所有UI组件通过Qt的父子关系自动管理
}

void RegisterWidget::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setSpacing(0);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);

    // 确保窗口填满整个区域
    this->setContentsMargins(0, 0, 0, 0);

    // 创建滚动区域
    QScrollArea *scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setObjectName("registerScrollArea");

    // 创建主容器 - 使用百分比布局
    QWidget *mainContainer = new QWidget();
    mainContainer->setObjectName("registerMainContainer");

    QHBoxLayout *mainHLayout = new QHBoxLayout(mainContainer);
    mainHLayout->setContentsMargins(0, 0, 0, 0);
    mainHLayout->setSpacing(0);

    // 左侧空白区域 (5%)
    QWidget *leftSpacer = new QWidget();
    leftSpacer->setObjectName("spacerWidget");

    // 中央表单区域 (90%)
    QWidget *centerWidget = new QWidget();
    centerWidget->setObjectName("registerCenterWidget");

    // 右侧空白区域 (5%)
    QWidget *rightSpacer = new QWidget();
    rightSpacer->setObjectName("spacerWidget");

    // 设置比例：左5% 中90% 右5%
    mainHLayout->addWidget(leftSpacer, 1);
    mainHLayout->addWidget(centerWidget, 18);
    mainHLayout->addWidget(rightSpacer, 1);

    QVBoxLayout *centerLayout = new QVBoxLayout(centerWidget);
    centerLayout->setSpacing(15);
    centerLayout->setContentsMargins(25, 5, 25, 20); // 大幅减少顶部边距

    // 重新设计的头部区域 - 左图标 + 中间文字 + 右装饰
    QWidget *headerWidget = new QWidget();
    headerWidget->setObjectName("registerHeader");
    QHBoxLayout *headerLayout = new QHBoxLayout(headerWidget);
    headerLayout->setSpacing(20);
    headerLayout->setContentsMargins(0, 0, 0, 0);

    // 左侧Logo图标 - 减小尺寸
    m_logoLabel = new QLabel();
    m_logoLabel->setAlignment(Qt::AlignCenter);
    m_logoLabel->setFixedSize(38, 38);
    m_logoLabel->setText("🎮");
    m_logoLabel->setObjectName("registerLogo");
    headerLayout->addWidget(m_logoLabel);

    // 中间标题区域 - 居中对齐，减小字体
    QWidget *titleWidget = new QWidget();
    QVBoxLayout *titleLayout = new QVBoxLayout(titleWidget);
    titleLayout->setSpacing(2);
    titleLayout->setContentsMargins(0, 0, 0, 0);

    m_titleLabel = new QLabel("创建新账户");
    m_titleLabel->setAlignment(Qt::AlignCenter);
    m_titleLabel->setObjectName("registerTitle");
    titleLayout->addWidget(m_titleLabel);

    QLabel *subtitleLabel = new QLabel("加入我们的游戏社区，开启精彩旅程");
    subtitleLabel->setAlignment(Qt::AlignCenter);
    subtitleLabel->setObjectName("registerSubtitle");
    titleLayout->addWidget(subtitleLabel);

    headerLayout->addWidget(titleWidget, 1); // 给标题区域更多空间

    // 右侧装饰图标 - 减小尺寸
    QLabel *decorIcon = new QLabel();
    decorIcon->setText("⭐");
    decorIcon->setAlignment(Qt::AlignCenter);
    decorIcon->setObjectName("registerDecorIcon");
    decorIcon->setFixedSize(38, 38);
    headerLayout->addWidget(decorIcon);

    centerLayout->addWidget(headerWidget);

    // 现代化表单容器
    QWidget *formContainer = new QWidget();
    formContainer->setObjectName("modernFormContainer");
    QVBoxLayout *formLayout = new QVBoxLayout(formContainer);
    formLayout->setSpacing(12);
    formLayout->setContentsMargins(25, 15, 25, 20);

    // 创建单列垂直布局的表单
    QWidget *formFieldsWidget = new QWidget();
    QVBoxLayout *fieldsLayout = new QVBoxLayout(formFieldsWidget);
    fieldsLayout->setSpacing(12);
    fieldsLayout->setContentsMargins(0, 0, 0, 0);

    // 用户名字段
    QWidget *usernameField = createInputField("👤", "用户名", "3-20个字符，字母数字下划线", m_usernameEdit, m_usernameHintLabel);
    connect(m_usernameEdit, &QLineEdit::textChanged, this, &RegisterWidget::onUsernameChanged);
    fieldsLayout->addWidget(usernameField);

    // 邮箱字段
    QWidget *emailField = createInputField("📧", "邮箱地址", "请输入有效的邮箱地址", m_emailEdit, m_emailHintLabel);
    connect(m_emailEdit, &QLineEdit::textChanged, this, &RegisterWidget::onEmailChanged);
    fieldsLayout->addWidget(emailField);

    // 密码字段
    QWidget *passwordField = createInputField("🔒", "密码", "至少8个字符，包含字母和数字", m_passwordEdit, m_passwordHintLabel);
    m_passwordEdit->setEchoMode(QLineEdit::Password);
    connect(m_passwordEdit, &QLineEdit::textChanged, this, &RegisterWidget::onPasswordChanged);
    fieldsLayout->addWidget(passwordField);

    // 确认密码字段
    QWidget *confirmField = createInputField("🔐", "确认密码", "请再次输入密码", m_confirmPasswordEdit, m_confirmPasswordHintLabel);
    m_confirmPasswordEdit->setEchoMode(QLineEdit::Password);
    connect(m_confirmPasswordEdit, &QLineEdit::textChanged, this, &RegisterWidget::onConfirmPasswordChanged);
    fieldsLayout->addWidget(confirmField);

    formLayout->addWidget(formFieldsWidget);

    // 密码强度指示器
    m_passwordStrengthLabel = new QLabel("密码强度: 未设置");
    m_passwordStrengthLabel->setObjectName("strengthLabel");
    formLayout->addWidget(m_passwordStrengthLabel);

    // 选项区域
    QWidget *optionsWidget = new QWidget();
    QVBoxLayout *optionsLayout = new QVBoxLayout(optionsWidget);
    optionsLayout->setSpacing(15);
    optionsLayout->setContentsMargins(0, 0, 0, 0);

    // 显示密码选项
    m_showPasswordCheck = new QCheckBox("显示密码");
    m_showPasswordCheck->setObjectName("modernCheckbox");
    connect(m_showPasswordCheck, &QCheckBox::toggled, this, &RegisterWidget::onShowPasswordToggled);
    optionsLayout->addWidget(m_showPasswordCheck);

    // 同意条款选项
    m_agreeTermsCheck = new QCheckBox("我已阅读并同意 用户协议 和 隐私政策");
    m_agreeTermsCheck->setObjectName("modernCheckbox");
    optionsLayout->addWidget(m_agreeTermsCheck);

    formLayout->addWidget(optionsWidget);

    centerLayout->addWidget(formContainer);

    // 按钮区域
    QWidget *buttonContainer = new QWidget();
    QVBoxLayout *buttonLayout = new QVBoxLayout(buttonContainer);
    buttonLayout->setSpacing(20);
    buttonLayout->setContentsMargins(0, 20, 0, 0);

    // 注册按钮
    m_registerButton = new QPushButton("🚀 创建账户");
    m_registerButton->setObjectName("modernPrimaryButton");
    m_registerButton->setDefault(true);
    m_registerButton->setMinimumHeight(45); // 增加按钮高度
    connect(m_registerButton, &QPushButton::clicked, this, &RegisterWidget::onRegisterClicked);
    buttonLayout->addWidget(m_registerButton);

    // 分隔线
    QFrame *separator = new QFrame();
    separator->setObjectName("separator");
    separator->setFrameShape(QFrame::HLine);
    separator->setFrameShadow(QFrame::Sunken);
    buttonLayout->addWidget(separator);

    // 返回登录链接
    QHBoxLayout *loginLinkLayout = new QHBoxLayout();
    QLabel *hasAccountLabel = new QLabel("已有账户?");
    hasAccountLabel->setObjectName("hintLabel");

    m_backToLoginButton = new QPushButton("立即登录");
    m_backToLoginButton->setObjectName("secondaryButton");
    connect(m_backToLoginButton, &QPushButton::clicked, this, &RegisterWidget::onBackToLoginClicked);

    loginLinkLayout->addStretch();
    loginLinkLayout->addWidget(hasAccountLabel);
    loginLinkLayout->addWidget(m_backToLoginButton);
    loginLinkLayout->addStretch();

    buttonLayout->addLayout(loginLinkLayout);
    centerLayout->addWidget(buttonContainer);

    // 状态显示
    m_statusLabel = new QLabel();
    m_statusLabel->setAlignment(Qt::AlignCenter);
    m_statusLabel->setObjectName("statusLabel");
    m_statusLabel->setWordWrap(true);
    centerLayout->addWidget(m_statusLabel);

    m_progressBar = new QProgressBar();
    m_progressBar->setVisible(false);
    m_progressBar->setObjectName("modernProgressBar");
    centerLayout->addWidget(m_progressBar);

    centerLayout->addStretch();

    // 设置滚动区域
    scrollArea->setWidget(mainContainer);

    // 将滚动区域添加到主布局
    m_mainLayout->addWidget(scrollArea);

    // 设置焦点
    m_usernameEdit->setFocus();
}

QWidget* RegisterWidget::createInputField(const QString &icon, const QString &label, const QString &placeholder, QLineEdit *&lineEdit, QLabel *&hintLabel)
{
    QWidget *field = new QWidget();
    field->setObjectName("inputField");

    QVBoxLayout *fieldLayout = new QVBoxLayout(field);
    fieldLayout->setContentsMargins(0, 0, 0, 0);
    fieldLayout->setSpacing(8);

    // 标签容器
    QWidget *labelContainer = new QWidget();
    QHBoxLayout *labelLayout = new QHBoxLayout(labelContainer);
    labelLayout->setContentsMargins(0, 0, 0, 0);
    labelLayout->setSpacing(8);

    // 图标标签 - 缩小尺寸
    QLabel *iconLabel = new QLabel(icon);
    iconLabel->setObjectName("inputIcon");
    iconLabel->setFixedSize(14, 14);
    iconLabel->setAlignment(Qt::AlignCenter);

    // 文字标签
    QLabel *textLabel = new QLabel(label);
    textLabel->setObjectName("inputLabel");

    labelLayout->addWidget(iconLabel);
    labelLayout->addWidget(textLabel);
    labelLayout->addStretch();

    // 输入框容器 - 增加最小高度
    QWidget *inputContainer = new QWidget();
    inputContainer->setObjectName("inputContainer");
    inputContainer->setMinimumHeight(40); // 设置最小高度
    QHBoxLayout *inputLayout = new QHBoxLayout(inputContainer);
    inputLayout->setContentsMargins(12, 10, 12, 10);
    inputLayout->setSpacing(0);

    // 创建输入框 - 设置最小尺寸
    lineEdit = new QLineEdit();
    lineEdit->setObjectName("modernInput");
    lineEdit->setPlaceholderText(placeholder);
    lineEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
    lineEdit->setMinimumHeight(18); // 设置最小高度
    lineEdit->setMinimumWidth(180); // 设置最小宽度

    inputLayout->addWidget(lineEdit);

    // 提示标签
    hintLabel = new QLabel();
    hintLabel->setObjectName("hintLabel");
    hintLabel->setWordWrap(true);
    hintLabel->hide(); // 默认隐藏

    fieldLayout->addWidget(labelContainer);
    fieldLayout->addWidget(inputContainer);
    fieldLayout->addWidget(hintLabel);

    return field;
}

void RegisterWidget::applyStyles()
{
    setStyleSheet(QString(R"(
        QWidget {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 %1, stop:0.5 #34495E, stop:1 #2C3E50);
            color: %2;
            font-family: 'Microsoft YaHei', 'Segoe UI', Arial, sans-serif;
        }

        #registerScrollArea {
            background: transparent;
            border: none;
        }

        #spacerWidget {
            background: transparent;
        }

        #registerMainContainer {
            background: transparent;
        }

        #registerCenterWidget {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(44, 62, 80, 0.95), stop:1 rgba(52, 73, 94, 0.95));
            border-radius: 20px;
            margin: 20px 0;
            border: 2px solid rgba(74, 144, 226, 0.4);
            /* 移除不支持的box-shadow属性 */
        }

        #registerHeader {
            background: transparent;
            margin-bottom: 10px;
        }

        #registerLogo {
            font-size: 30px;
            color: %3;
            /* 移除不支持的text-shadow属性 */
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 rgba(74, 144, 226, 0.2), stop:1 rgba(52, 152, 219, 0.2));
            border-radius: 19px;
            border: 2px solid rgba(74, 144, 226, 0.4);
        }

        #registerDecorIcon {
            font-size: 26px;
            color: #E67E22;
            /* 移除不支持的text-shadow属性 */
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 rgba(230, 126, 34, 0.2), stop:1 rgba(211, 84, 0, 0.2));
            border-radius: 19px;
            border: 2px solid rgba(230, 126, 34, 0.4);
        }

        #registerTitle {
            color: %2;
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 3px;
            /* 移除不支持的text-shadow属性 */
        }

        #registerSubtitle {
            color: #BDC3C7;
            font-size: 12px;
            font-weight: 400;
            margin-bottom: 8px;
        }

        #modernFormContainer {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(52, 73, 94, 0.8), stop:1 rgba(44, 62, 80, 0.8));
            border-radius: 15px;
            /* 移除不支持的box-shadow属性 */
            border: 1px solid rgba(74, 144, 226, 0.4);
        }

        /* 输入字段样式 */
        #inputField {
            margin-bottom: 8px;
        }

        #inputIcon {
            color: %3;
            font-size: 14px;
            font-weight: bold;
        }

        #inputLabel {
            color: %2;
            font-size: 13px;
            font-weight: 600;
            /* 移除不支持的text-shadow属性 */
        }

        #inputContainer {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(52, 73, 94, 0.7), stop:1 rgba(44, 62, 80, 0.7));
            border: 2px solid rgba(74, 144, 226, 0.4);
            border-radius: 10px;
            margin-top: 5px;
            min-height: 40px;
        }

        #inputContainer:hover {
            border-color: rgba(74, 144, 226, 0.8);
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(58, 83, 104, 0.8), stop:1 rgba(52, 73, 94, 0.8));
            /* 移除不支持的transform属性 */
        }

        #inputContainer:focus-within {
            border-color: %3;
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(58, 83, 104, 0.9), stop:1 rgba(52, 73, 94, 0.9));
            /* 移除不支持的box-shadow和transform属性 */
        }

        #modernInput {
            background: transparent;
            border: none;
            font-size: 14px;
            color: %2;
            min-height: 18px;
        }

        #modernInput:focus {
            outline: none;
        }

        #modernInput::placeholder {
            color: #95A5A6;
            font-style: italic;
        }

        #hintLabel {
            color: #E74C3C;
            font-size: 12px;
            margin-top: 5px;
            padding-left: 5px;
            /* 移除不支持的text-shadow属性 */
        }

        #strengthLabel {
            color: #BDC3C7;
            font-size: 13px;
            font-weight: 500;
            margin: 10px 0;
            padding: 8px 12px;
            background: rgba(52, 73, 94, 0.6);
            border-radius: 8px;
            border-left: 4px solid %3;
        }

        #modernCheckbox {
            color: %2;
            font-size: 14px;
            spacing: 8px;
        }

        #modernCheckbox::indicator {
            width: 18px;
            height: 18px;
            border-radius: 4px;
            border: 2px solid rgba(74, 144, 226, 0.6);
            background: rgba(44, 62, 80, 0.8);
        }

        #modernCheckbox::indicator:checked {
            background: %3;
            border-color: %3;
            image: url();
        }

        #modernPrimaryButton {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %3, stop:1 #3498DB);
            color: white;
            border: none;
            border-radius: 12px;
            padding: 15px 30px;
            font-size: 16px;
            font-weight: bold;
            min-height: 20px;
        }

        #modernPrimaryButton:hover {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #5DADE2, stop:1 #4A90E2);
            /* 移除不支持的box-shadow和transform属性 */
        }

        #modernPrimaryButton:pressed {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #3498DB, stop:1 #2980B9);
        }

        #secondaryButton {
            background: transparent;
            color: %3;
            border: 2px solid rgba(74, 144, 226, 0.6);
            border-radius: 8px;
            padding: 8px 16px;
            font-size: 14px;
            font-weight: 600;
        }

        #secondaryButton:hover {
            background: rgba(74, 144, 226, 0.8);
            color: white;
            border-color: %3;
        }

        #separator {
            background: rgba(74, 144, 226, 0.3);
            margin: 15px 0;
        }

        #hintLabel {
            color: #BDC3C7;
            font-size: 14px;
        }

        #modernProgressBar {
            border: none;
            border-radius: 6px;
            background: #E9ECEF;
            height: 8px;
        }

        #modernProgressBar::chunk {
            background: %3;
            border-radius: 6px;
        }

        #registerScrollArea QScrollBar:vertical {
            background-color: rgba(52, 73, 94, 0.3);
            width: 8px;
            border-radius: 4px;
        }

        #registerScrollArea QScrollBar::handle:vertical {
            background-color: %3;
            border-radius: 4px;
            min-height: 20px;
        }
    )").arg(m_backgroundColor, m_textColor, m_primaryColor));
}

void RegisterWidget::onRegisterClicked()
{
    if (!validateForm()) {
        return;
    }

    setUIEnabled(false);
    m_progressBar->setVisible(true);
    m_statusLabel->setText("正在创建账户...");
    m_statusLabel->setStyleSheet("color: #3498DB; background-color: rgba(52, 152, 219, 0.1);");

    m_authService->registerUser(
        m_usernameEdit->text().trimmed(),
        m_passwordEdit->text(),
        m_emailEdit->text().trimmed()
    );
}

void RegisterWidget::onBackToLoginClicked()
{
    emit switchToLogin();
}

void RegisterWidget::onRegisterSucceeded()
{
    setUIEnabled(true);
    m_progressBar->setVisible(false);
    m_statusLabel->setText("账户创建成功! 请登录");
    m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(39, 174, 96, 0.1);").arg(m_successColor));
    
    clearForm();
    
    // 延迟切换到登录页面
    QTimer::singleShot(2000, this, &RegisterWidget::switchToLogin);
}

void RegisterWidget::onRegisterFailed(const QString &error)
{
    setUIEnabled(true);
    m_progressBar->setVisible(false);
    m_statusLabel->setText(error);
    m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
}

void RegisterWidget::onShowPasswordToggled(bool show)
{
    QLineEdit::EchoMode mode = show ? QLineEdit::Normal : QLineEdit::Password;
    m_passwordEdit->setEchoMode(mode);
    m_confirmPasswordEdit->setEchoMode(mode);
}

void RegisterWidget::onPasswordChanged()
{
    QString password = m_passwordEdit->text();
    updatePasswordStrength(password);
    
    if (password.isEmpty()) {
        m_passwordHintLabel->clear();
        return;
    }

    if (isValidPassword(password)) {
        m_passwordHintLabel->setText("✓ 密码格式正确");
        m_passwordHintLabel->setStyleSheet(QString("color: %1;").arg(m_successColor));
    } else {
        m_passwordHintLabel->setText("✗ 密码必须至少8个字符，包含字母和数字");
        m_passwordHintLabel->setStyleSheet(QString("color: %1;").arg(m_errorColor));
    }

    onConfirmPasswordChanged(); // 重新验证确认密码
}

void RegisterWidget::onConfirmPasswordChanged()
{
    QString password = m_passwordEdit->text();
    QString confirmPassword = m_confirmPasswordEdit->text();
    
    if (confirmPassword.isEmpty()) {
        m_confirmPasswordHintLabel->clear();
        return;
    }

    if (password == confirmPassword) {
        m_confirmPasswordHintLabel->setText("✓ 密码匹配");
        m_confirmPasswordHintLabel->setStyleSheet(QString("color: %1;").arg(m_successColor));
    } else {
        m_confirmPasswordHintLabel->setText("✗ 密码不匹配");
        m_confirmPasswordHintLabel->setStyleSheet(QString("color: %1;").arg(m_errorColor));
    }
}

void RegisterWidget::onUsernameChanged()
{
    QString username = m_usernameEdit->text();
    
    if (username.isEmpty()) {
        m_usernameHintLabel->clear();
        return;
    }

    if (isValidUsername(username)) {
        m_usernameHintLabel->setText("✓ 用户名格式正确");
        m_usernameHintLabel->setStyleSheet(QString("color: %1;").arg(m_successColor));
    } else {
        m_usernameHintLabel->setText("✗ 用户名只能包含字母、数字、下划线，长度3-20个字符");
        m_usernameHintLabel->setStyleSheet(QString("color: %1;").arg(m_errorColor));
    }
}

void RegisterWidget::onEmailChanged()
{
    QString email = m_emailEdit->text();

    if (email.isEmpty()) {
        m_emailHintLabel->clear();
        return;
    }

    if (isValidEmail(email)) {
        m_emailHintLabel->setText("✓ 邮箱格式正确");
        m_emailHintLabel->setStyleSheet(QString("color: %1;").arg(m_successColor));
    } else {
        m_emailHintLabel->setText("✗ 请输入有效的邮箱地址");
        m_emailHintLabel->setStyleSheet(QString("color: %1;").arg(m_errorColor));
    }
}

bool RegisterWidget::validateForm()
{
    QString username = m_usernameEdit->text().trimmed();
    QString email = m_emailEdit->text().trimmed();
    QString password = m_passwordEdit->text();
    QString confirmPassword = m_confirmPasswordEdit->text();

    if (username.isEmpty()) {
        m_statusLabel->setText("请输入用户名");
        m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_usernameEdit->setFocus();
        return false;
    }

    if (!isValidUsername(username)) {
        m_statusLabel->setText("用户名格式不正确");
        m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_usernameEdit->setFocus();
        return false;
    }

    if (email.isEmpty()) {
        m_statusLabel->setText("请输入邮箱地址");
        m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_emailEdit->setFocus();
        return false;
    }

    if (!isValidEmail(email)) {
        m_statusLabel->setText("邮箱格式不正确");
        m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_emailEdit->setFocus();
        return false;
    }

    if (password.isEmpty()) {
        m_statusLabel->setText("请输入密码");
        m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_passwordEdit->setFocus();
        return false;
    }

    if (!isValidPassword(password)) {
        m_statusLabel->setText("密码格式不正确");
        m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_passwordEdit->setFocus();
        return false;
    }

    if (password != confirmPassword) {
        m_statusLabel->setText("两次输入的密码不一致");
        m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_confirmPasswordEdit->setFocus();
        return false;
    }

    if (!m_agreeTermsCheck->isChecked()) {
        m_statusLabel->setText("请同意用户协议和隐私政策");
        m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        return false;
    }

    return true;
}

bool RegisterWidget::isValidEmail(const QString &email)
{
    QRegularExpression emailRegex(R"(^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$)");
    return emailRegex.match(email).hasMatch();
}

bool RegisterWidget::isValidPassword(const QString &password)
{
    if (password.length() < 8) {
        return false;
    }

    // 检查是否包含字母和数字
    bool hasLetter = false;
    bool hasDigit = false;

    for (const QChar &ch : password) {
        if (ch.isLetter()) {
            hasLetter = true;
        } else if (ch.isDigit()) {
            hasDigit = true;
        }
    }

    return hasLetter && hasDigit;
}

bool RegisterWidget::isValidUsername(const QString &username)
{
    if (username.length() < 3 || username.length() > 20) {
        return false;
    }

    QRegularExpression usernameRegex(R"(^[a-zA-Z0-9_]+$)");
    return usernameRegex.match(username).hasMatch();
}

void RegisterWidget::updatePasswordStrength(const QString &password)
{
    if (password.isEmpty()) {
        m_passwordStrengthLabel->clear();
        return;
    }

    int score = 0;
    QString strengthText;
    QString strengthColor;

    // 长度检查
    if (password.length() >= 8) score++;
    if (password.length() >= 12) score++;

    // 字符类型检查
    bool hasLower = false, hasUpper = false, hasDigit = false, hasSpecial = false;
    for (const QChar &ch : password) {
        if (ch.isLower()) hasLower = true;
        else if (ch.isUpper()) hasUpper = true;
        else if (ch.isDigit()) hasDigit = true;
        else hasSpecial = true;
    }

    if (hasLower) score++;
    if (hasUpper) score++;
    if (hasDigit) score++;
    if (hasSpecial) score++;

    // 评估强度
    if (score <= 2) {
        strengthText = "弱";
        strengthColor = m_errorColor;
    } else if (score <= 4) {
        strengthText = "中等";
        strengthColor = m_warningColor;
    } else {
        strengthText = "强";
        strengthColor = m_successColor;
    }

    m_passwordStrengthLabel->setText(strengthText);
    m_passwordStrengthLabel->setStyleSheet(QString("color: %1;").arg(strengthColor));
}

void RegisterWidget::setUIEnabled(bool enabled)
{
    m_usernameEdit->setEnabled(enabled);
    m_emailEdit->setEnabled(enabled);
    m_passwordEdit->setEnabled(enabled);
    m_confirmPasswordEdit->setEnabled(enabled);
    m_showPasswordCheck->setEnabled(enabled);
    m_agreeTermsCheck->setEnabled(enabled);
    m_registerButton->setEnabled(enabled);
    m_backToLoginButton->setEnabled(enabled);
}

void RegisterWidget::clearForm()
{
    m_usernameEdit->clear();
    m_emailEdit->clear();
    m_passwordEdit->clear();
    m_confirmPasswordEdit->clear();
    m_showPasswordCheck->setChecked(false);
    m_agreeTermsCheck->setChecked(false);
    m_statusLabel->clear();

    // 清空提示标签
    m_usernameHintLabel->clear();
    m_emailHintLabel->clear();
    m_passwordHintLabel->clear();
    m_confirmPasswordHintLabel->clear();
    m_passwordStrengthLabel->clear();
}
